/*
 * 楼盘基本信息
 * @author 狮子
 * @time 2018/9/19
 * @since 1.0.0
 * */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form, Row, Col, Input, Cascader, Tag, Icon, DatePicker, Select, Button, Upload, Modal, Divider, Radio, Popover, Checkbox } from 'antd'
const FormItem = Form.Item;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'

// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './premisesDetailStyle.less'
import cx from 'classnames'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import moment from "moment";
import Draggable, { DraggableCore } from 'react-draggable';
import markImg from '../../../../../assets/img/premise_mark.png'
import markImgDisable from '../../../../../assets/img/premise_mark_disable.png'
import { cloneDeep } from 'lodash'
import { houseTypeList } from './premisesDetailServ';
const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 15 },
};
const checkboxLayout = {
  labelCol: { span: 2 },
  wrapperCol: { span: 22 },
};

const RouteView = function ({ dispatch, model, form }) {
  //楼栋开始拖
  function markerStart(e, position) {
    console.log(e, position)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { currStart: [position.lastX, position.lastY], }
    });
  }
  //楼栋坐标拖拽停止
  function markerDraf(e, position) {
    console.log(e, position);
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { currPremiseMarker: [position.lastX, position.lastY], }
    });
  }
  //楼栋坐标弹框确定
  function confirmMarker() {
    let premiseMarkerCopy
        premiseMarkerCopy = cloneDeep(premiseMarker);
    
    //console.log(premiseMarker,'premiseMarker',currPremiseMarker,'currPremiseMarker')
    if (currPremiseMarker && currPremiseMarker.length) {

      premiseMarkerCopy.current.marker = [
        premiseMarker.current.marker[0] + currPremiseMarker[0],
        premiseMarker.current.marker[1] + currPremiseMarker[1],
      ]
      console.log('premiseMarkerCopy:', premiseMarkerCopy)
    };

    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        premiseMarker: premiseMarkerCopy,
        premiseMarkerVisible: false
      }
    });
  }
  //取消坐标弹框
  function cancelMarker() {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { premiseMarkerVisible: false }
    });
  }
  //Markmodel
  function showMarker() {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { premiseMarkerVisible: true }
    });
  }
  function inputChange(e, type,idx) {
    if (type == 'parentProductId' ) {
      
      dispatch({ type: `${namespace}/getBuildingPic`, payload: { productId: e } });
      let estateName = estateList.filter((item,idx)=>item.productId==e)[0].name
      dispatch({ type: `${namespace}/getHouseTypeList`, payload: { parentProductId: e,estateName} });
      //区数
      let zn = estateList.filter((item,idx)=>item.productId==e)[0].estateRegion
      console.log(zn)
      let region=zn&&zn.length==0?'0区':undefined
      form.setFieldsValue({region})
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { zone:estateList.filter((item,idx)=>item.productId==e)[0].estateRegion,buildInfo }
      });
    }
    buildInfo[type] = e
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { buildInfo }
    });
    
    console.log(e, type)
    
  }
  
  function onChange(value) {
    buildInfo.province = value[0]
    buildInfo.city = value[1]
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { buildInfo }
    });
    new Promise((resolve) => {
      dispatch({
        type: `${namespace}/getEstateList`,
        payload: { province: value[0], city: value[1],resolve}
      })
    }).then((res) => {
      console.log(res)
      if(res[0]){
        dispatch({ type: `${namespace}/getBuildingPic`, payload: { productId: res[0]?res[0].productId:null} });
      }
      form.setFieldsValue({parentProductId:res[0]?res[0].productId:null})
      let region = res[0].zone&&res[0].zone.length==0?'0区':undefined
      console.log('region---',region)
      form.setFieldsValue({region})
      
      buildInfo.parentProductId = res[0]?res[0].productId:null
      buildInfo.region = region
      dispatch({
        type: `${namespace}/updateStore`,
        payload: { buildInfo }
      });
      let  estateName =res.filter((item,idx)=>item.productId==res[0].productId)[0].name
      dispatch({ type: `${namespace}/getHouseTypeList`, payload: { parentProductId:res[0]?res[0].productId:null,estateName} });
      if(res[0]){
        dispatch({
          type: `${namespace}/updateStore`,
          payload: { zone:res.filter((item,idx)=>item.productId==res[0].productId)[0].estateRegion}
        });
      }else{
        form.setFieldsValue({region:null})
      }
      
    })
    
  }
  
  //获取区数选项
  function getOption() {

    if (zone&&zone.length > 0) {
      return zone.map((item, idx) => {
        return <Select.Option key={idx} value={item}>{item}</Select.Option>
      })
    } else {
      return null
    }
  }
  // 跳转
  function detailSkip(type, productId) {
    hashHistory.push({
      pathname: '/home/buildingAdmin/baseinfoDetail',
      query: { actionType: type, productId }
    });

  }
  // 获取项目选项
  function getPorjectOption() {
    return estateList.map((item, idx) => {
      return <Select.Option key={idx} value={item.productId}>{item.name}</Select.Option>
    })
  }
  //获取户型选项
  function getHouseOption() {
    return houseList.map((item, idx) => {
      return <Popover placement="bottomRight" content={content} key={idx} onVisibleChange={(e)=>{
        if(e){
          dispatch({
            type:`${namespace}/getHouseTypeDetail`,
            payload: {productId:item.productId }
          })
        }
        console.log(e,item)
      }}>
        <Checkbox value={item.productId}>{item.name}</Checkbox>
      </Popover>

    })
  }
  //提交
  function submit() {
    form.validateFields((err, values) => {
      if(!err){
        dispatch({
          type: `${namespace}/sumbit`,
          payload: values
        })
      }
    });
  }
  //今天
  function disabledDate(current) {
    // Can not select days before today and today
    return current && current < moment().startOf('day');
  }
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  const { premiseMarker, currPremiseMarker, premiseMarkerVisible, areaList, buildInfo, estateList, houseList,buildingPic,houseTypeDetail,actionType,zone,disabled } = modelObj
  // modelObj.xxx获取model中状态机的值
  console.log(zone)
  let content = (
    <div style={{width:"1000px"}}>
      <Row>
        <Col span={24}>户型信息</Col>
      </Row>
      <Row>
        <Col span={6}> 户型编号：{houseTypeDetail.productId?houseTypeDetail.productId:null}</Col>
        <Col span={6}> 户型名称：{houseTypeDetail.name?houseTypeDetail.name:null}</Col>
        <Col span={6}> 户型：{houseTypeDetail.layoutName?houseTypeDetail.layoutName:null}</Col>
        <Col span={6}> 所属项目：{houseTypeDetail.productId?houseTypeDetail.productId:null}</Col>
      </Row>
      <Row>
        <Col span={6}> 建筑面积：{houseTypeDetail.buildingArea?houseTypeDetail.buildingArea:null}</Col>
        <Col span={6}> 套内面积：{houseTypeDetail.innerArea?houseTypeDetail.innerArea:null}</Col>
        <Col span={6}> 参考总价：{houseTypeDetail.totalPrice?houseTypeDetail.totalPrice:null}</Col>
      </Row>
      <Row>
        <Col span={2}>
          标签：
        </Col>
        <Col span={22}>
          {
            houseTypeDetail.tag&&houseTypeDetail.tag.length>0?houseTypeDetail.tag.map((item,idx)=>{
              return <span key={idx}>{item},</span>
            }):null
          }
        </Col>
      </Row>
    </div>
  );
  return (
    <div className={cx('pageLayout')}>
      {
        premiseMarkerVisible && <Modal title={null}
          visible={premiseMarkerVisible}
          className={'model'}
          width={800}
          footer={null}
          closable={false}
          >
          <div>
            <div className={styles.flex}> <div className={styles.title}>楼栋标注</div> <div><Button onClick={e=>cancelMarker()} style={{marginRight:20}}>取消</Button> <Button disabled={actionType == "add" || actionType == "edit" ? false : true} type='primary' onClick={e=>confirmMarker()}>确定</Button></div></div>
            <div style={{ height: 800, width: '100%', position: 'relative',background:"url('"+buildingPic.building+"') no-repeat",backgroundSize: "100%,100%"}}>
              <Draggable bounds="parent" zIndex={300} onStop={markerDraf}>
                <div className={cx(styles.draggableBlock, 'fl')} style={{ position: 'absolute', zIndex: 200, top: premiseMarker.current.marker[1], left: premiseMarker.current.marker[0] }}>
                  <img src={markImg} />
                  <div style={{color:'#0877FD'}}>{premiseMarker.current.label}</div>
                </div>
              </Draggable>
              {
                premiseMarker.others && premiseMarker.others.map((d, idx) => {
                  return <Draggable bounds="parent" disabled={true} key={idx}>
                    <div className={cx(styles.draggableBlock, 'fl')} style={{ position: 'absolute', top: d.marker[0], left: d.marker[1] }}>
                      <img src={markImgDisable} />
                      <div>{d.label}</div>
                    </div>
                  </Draggable>
                })
              }
            </div>
          </div>
         
        </Modal>
      }

      <div className={cx('public_listMain')}>
        <div className="functionButton">
          {/* <Button type='primary'>预览</Button> */}
          {actionType == "add" || actionType == "edit" ?<Button type='primary' onClick={e => submit(1)} disabled={disabled} loading={modelObj.btnLoading}>提交</Button>
            : null}
        </div>
      </div>
      <div>
        <CollapsiblePanels title="楼栋信息" hideUpDownBtn={true} >
          <Row>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout}
                label="所属城市">
                {getFieldDecorator(`location`, {
                  initialValue:[`${buildInfo.province}`,`${buildInfo.city}` ],
                  rules: [
                    {
                      required: true, validator: (rule, value, callback) => {
                        console.log(buildInfo.city)
                        if (typeof (buildInfo.city||buildInfo.province) == 'undefined') {
                          callback('请选择所属城市')
                        } else {
                          callback()
                        }
                      }
                    }
                  ],
                })(
                      <Cascader options={areaList} placeholder="请选择所属城市" disabled={actionType == 'check' || actionType == 'edit' } onChange={onChange} placeholder={actionType == 'check'?"":'请选择所属项目'}  />
                )}
              </FormItem>
            </Col>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout}
                label="所属项目">
                {getFieldDecorator(`parentProductId`, {
                  initialValue:[buildInfo.parentProductId],
                  rules: [
                    {
                      required: true, validator: (rule, value, callback) => {
                        console.log(buildInfo.parentProductId)
                        if (typeof (buildInfo.parentProductId) == 'undefined') {
                          callback('请选择项目')
                        } else {
                          callback()
                        }
                      }
                    }
                  ],
                })(
                  <Select
                  notFoundContent={'该省市中无楼盘'}
                  disabled={actionType == 'check' || actionType == 'edit' }
                  placeholder="请选择项目"
                  onChange={(e,idx) => inputChange(e, 'parentProductId',idx)} >
                  {getPorjectOption()}
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout}
                label="所属分期">
                {getFieldDecorator(`region`, {
                  initialValue: buildInfo.region ?buildInfo.region:"",
                  rules: [
                    { required:false, whitespace: true, message: '请选择所属分期' },
                  ],
                })(<Select
                  disabled={actionType == 'check'}
                  showSearch
                  placeholder="请选择所属分期"
                  onChange={(e) => inputChange(e, 'region')}>
                  {getOption()}
                </Select>)}
              </FormItem>
            </Col>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout}
                label="所属座">
                {getFieldDecorator(`seat`, {
                  initialValue: buildInfo.seat,
                  rules: [
                    { required: true, whitespace: true, message: '请输入所属座' },
                  ],
                })(<Input placeholder={actionType == 'check'?"":'请输入所属座'} disabled={actionType == 'check'} onChange={(e) => inputChange(e.target.value, 'seat')} />)}
              </FormItem>
            </Col>

          </Row>
          <Row>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout}
                label="层数">
                {getFieldDecorator(`layerCount`, {
                  initialValue: buildInfo.layerCount?buildInfo.layerCount+'': '',
                  rules: [
                    { required: false, whitespace: true, message: '请输入层数' },
                    { pattern:/\d/,message: '请输入数字'}
                  ],
                  
                })(<Input placeholder={actionType == 'check'?"":'请输入层数'} disabled={actionType == 'check'} onChange={(e) => inputChange(e.target.value, 'layerCount')} />)}
              </FormItem>
            </Col>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout}
                label="规划户数">
                {getFieldDecorator(`houseCount`, {
                  initialValue:  buildInfo.houseCount?buildInfo.houseCount+'': '',
                  rules: [
                    { required: false, whitespace: true, message: '请输入规划户数' },
                  ],
                  getValueFromEvent: (event) => {
                    return event.target.value.replace(/\D/g,'')
                  },
                })(<Input placeholder={actionType == 'check'?"":'请输入规划户数'} disabled={actionType == 'check'} onChange={(e) => inputChange(e.target.value, 'houseCount')} />)}
              </FormItem>
            </Col>
            <Col className="unitCount" span={6}>
              <FormItem {...formItemLayout}
                label="单元数">
                {getFieldDecorator(`unitCount`, {
                  initialValue:buildInfo.unitCount?buildInfo.unitCount+'': '',
                  rules: [
                    { required: false, whitespace: true, message: '请选择单元数' },
                  ],
                  getValueFromEvent: (event) => {
                    return event.target.value.replace(/\D/g,'')
                  },
                })(<Input placeholder={actionType == 'check'?"":'填写此楼栋所含单元数'} disabled={actionType == 'check'} onChange={(e) => inputChange(e.target.value, 'unitCount')} />)}
              </FormItem>
            </Col>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout}
                label="开盘日期">
                {getFieldDecorator(`openingTime`, {
                  initialValue: buildInfo.openingTime ? moment(buildInfo.openingTime) : null,
                  rules: [
                    { required: false, type: 'object', whitespace: true, message: '请选择开盘日期' },
                  ],
                })(<DatePicker disabled={actionType == 'check'} onChange={(e, val) => inputChange(val, 'openingTime')} placeholder={actionType == 'check'?"":"请选择开盘日期"} />)}
              </FormItem>
            </Col>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout}
                label="产权年限">
                {getFieldDecorator(`propertyRight`, {
                  initialValue: buildInfo.propertyRight,
                  rules: [
                    { required: false, whitespace: true, message: '请输入产权年限' },
                  ],
                })(<Input disabled={actionType == 'check'} placeholder={actionType == 'check'?"":"请输入产权年限"} onChange={(e) => inputChange(e.target.value, 'propertyRight')} />)}
              </FormItem>
            </Col>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout}
                label="交房日期">
                {getFieldDecorator(`submitTime`, {
                  initialValue: buildInfo.submitTime ? moment(buildInfo.submitTime) : null,
                  rules: [
                    { required: false, whitespace: true, type: 'object', message: '请选择交房日期' },
                  ],
                })(<DatePicker  disabled={actionType == 'check'} onChange={(e, val) => inputChange(val, 'submitTime')} placeholder={actionType == 'check'?"":"请选择"} />)}
              </FormItem>
            </Col>
           
            <Col className="col" span={6}>
              <FormItem {...formItemLayout}
                label="销售状态">
                {getFieldDecorator(`saleStatus`, {
                  initialValue:  buildInfo.saleStatus?buildInfo.saleStatus+'' : '',
                  rules: [
                    { required: true, whitespace: true, message: '请选择销售状态' },
                  ],
                })((<Select placeholder="请选择" disabled={actionType == 'check'} onChange={(val) => inputChange(val, 'saleStatus')} >
                  <Select.Option value="1">待售</Select.Option>
                  <Select.Option value="2">在售</Select.Option>
                  <Select.Option value="3">尾盘</Select.Option>
                  <Select.Option value="4">售罄</Select.Option>
                </Select>))}
              </FormItem>
            </Col>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout}
                label="楼栋标注">
                {getFieldDecorator(`premiseMarker`, {
                  rules: [
                    { required: false, validator: (rule, value, callback) => {
                      //console.log(premiseMarker.current.marker)
                      if (premiseMarker.current.marker&&premiseMarker.current.marker.length==0) {
                        //console.log(premiseMarker.current.marker)
                        callback('请选择楼栋标注')
                      } else {
                        callback()
                      }
                    } },
                  ],
                })(<span style={{ color: '#0877FD', cursor: "pointer" }} onClick={() => showMarker()}>{actionType == 'check'? '查看':'选择'}</span>)}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout}
                label="预售证名称">
                {getFieldDecorator(`preSalePermitName`, {
                  initialValue: buildInfo.preSalePermitName,
                  rules: [
                    { required: false, whitespace: true, message: '请输入预售证名称' },
                  ],
                })(<Input placeholder={actionType == 'check'?"":'请输入预售证名称'} disabled={actionType == 'check'} onChange={(e) => inputChange(e.target.value, 'preSalePermitName')} />)}
              </FormItem>
            </Col>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout}
                label="发证日期">
                {getFieldDecorator(`awardTime`, {
                  initialValue: buildInfo.awardTime ? moment(buildInfo.awardTime) : null,
                  rules: [
                    { required: false, whitespace: true, type: 'object', message: '请选择发证日期' },
                  ],
                })(<DatePicker disabled={actionType == 'check'} onChange={(e, val) => inputChange(val, 'awardTime')} placeholder={actionType == 'check'?"":"请选择"} />)}
              </FormItem>
            </Col>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout}
                label="建筑类型">
                {getFieldDecorator(`buildingType`, {
                  initialValue: buildInfo.buildingType,
                  rules: [
                    { required: false, whitespace: true, message: '请选择建筑类型' },
                  ],
                })((<Select placeholder={actionType == 'check'?"":'请选择建筑类型'} disabled={actionType == 'check'} onChange={(val) => inputChange(val, 'buildingType')} >
                  <Select.Option value="高层">高层</Select.Option>
                  <Select.Option value="洋房">洋房</Select.Option>
                  <Select.Option value="别墅">别墅</Select.Option>
                  <Select.Option value="双拼">双拼</Select.Option>
                  <Select.Option value="联排">联排</Select.Option>
                  <Select.Option value="叠墅">叠墅</Select.Option>
                  <Select.Option value="公寓">公寓</Select.Option>
                  <Select.Option value="写字楼">写字楼</Select.Option>
                  <Select.Option value="复式">复式</Select.Option>
                  <Select.Option value="商铺">商铺</Select.Option>
                  <Select.Option value="车位">车位</Select.Option>
                  <Select.Option value="储藏室">储藏室</Select.Option>
                </Select>))}
              </FormItem>
            </Col>
            <Col className="col" span={6}>
              <FormItem {...formItemLayout}
                label="	物业类型">
                {getFieldDecorator(`propertyType`, {
                  initialValue: buildInfo.propertyType,
                  rules: [
                    { required: false, whitespace: true, message: '请输入物业类型' },
                  ],
                })((<Input placeholder={actionType == 'check'?"":'商业/住宅'} disabled={actionType == 'check'} onChange={(e) => inputChange(e.target.value, 'propertyType')} />))}
              </FormItem>
            </Col>
          </Row>
          <Row>
            <FormItem
              {...checkboxLayout}
              label="含有户型">
              {getFieldDecorator(`houseTypeIds`, {
                initialValue: buildInfo.houseTypeIds,
                rules: [
                  { required: false, type: "array", whitespace: true, message: '请选择状态' },
                ],
              })(
                <Checkbox.Group style={{ width: '100%' }} disabled={actionType == 'check'} onChange={(e) => inputChange(e, 'houseTypeIds')}>
                  {getHouseOption()}
                </Checkbox.Group>
              )}
            </FormItem>
          </Row>

        </CollapsiblePanels>
      </div>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(RouteView))
